<template>
  <div class="banner">
    <div class="banner_top">
      <!-- 搜索框 -->
      <a-input-search
        class="search"
        v-model:value="keywords"
        :placeholder="$t('search.placeholder')"
        enter-button
        @search="onSearch"
        allowClear
      />
      <!-- 跳转添加 -->
      <a-space>
        <!-- 刷新页面 -->
        <a-button @click="refresh">
          <template #icon>
            <ReloadOutlined />
          </template>
          {{ $t("Banner.Refresh") }}
        </a-button>
        <!-- 添加 -->
        <a-button type="primary" @click="toAdd">
          <template #icon>
            <PlusOutlined />
          </template>
          {{ $t("Banner.Add") }}
        </a-button>
      </a-space>
    </div>
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :rowKey="(record) => record.id"
      :data-source="data"
      :row-selection="rowSelection"
      :pagination="false"
      :loading="isLoading"
      :scroll="{ y: 'calc(100vh - 288px' }"
    >
      <!-- 操作 -->
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-button-group>
            <a-button
              size="small"
              ghost
              type="primary"
              @click="toEdiort(record)"
              >{{ $t("Banner.Edit") }}</a-button
            >
            <a-button size="small" ghost danger @click="remove(true, record)">{{
              $t("Banner.Delete1")
            }}</a-button>
          </a-button-group>
        </template>

        <template v-if="column.dataIndex === 'pic'">
          <a-image :width="70" :height="60" :src="record.pic" />
        </template>

        <template v-if="column.dataIndex === 'status'">
          <a-tag color="#87d068" v-if="record.status">{{
            $t("Banner.Open")
          }}</a-tag>
          <a-tag color="#f50" v-else>{{ $t("Banner.Close") }}</a-tag>
        </template>
      </template>
    </a-table>
    <!-- 分页 -->
    <div class="footer">
      <a-button :disabled="selectedData.length === 0" @click="remove(false)">{{
        $t("Banner.Delete")
      }}</a-button>
      <a-pagination
        v-model:current="page"
        :total="total"
        :page-size-options="pageSizeOptions"
        show-size-changer
        @showSizeChange="onShowSizeChange"
        v-model:pageSize="limit"
        hideOnSinglePage
      >
        <template #buildOptionText="props">
          <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
        </template>
        <template #itemRender="{ type, originalElement }">
          <a v-if="type === 'prev'">{{ $t("Banner.Previous") }}</a>
          <a v-else-if="type === 'next'">{{ $t("Banner.Next") }}</a>
          <component :is="originalElement" v-else></component>
        </template>
      </a-pagination>
    </div>
  </div>
</template>

<script setup>
import {
  PlusOutlined,
  ExclamationCircleOutlined,
  ReloadOutlined,
} from "@ant-design/icons-vue";
import { Modal, message as Msg } from "ant-design-vue";
import columns from "./table_config";
import { getBanneListApi, delBannerApi } from "@/api/banner";
import { handlerPicPath } from "@/utils/tools";
import { createVNode, inject } from "vue";
const keywords = ref("");
const data = ref([]);
// 多选
const selectedData = ref([]);
// 当前页
const page = ref(1);
// 每页多少条
const limit = ref(2);
// 总条数
const total = ref(0);
//表格中的loading
const isLoading = ref(false);
// 每页多少条
const pageSizeOptions = ref(["10", "20", "30", "40", "50"]);
const onShowSizeChange = (current, pageSize) => {
  limit.value = pageSize;
  //current当前页 pageSize每页条数
  getList();
};

watch(page, () => {
  getList();
});

// 父调子刷新
const refresh = inject("refresh");

//请求数据
const getList = async () => {
  isLoading.value = true;
  const params = {
    page: page.value,
    limit: limit.value,
    keyword: keywords.value,
  };
  const res = await getBanneListApi(params);
  data.value = handlerPicPath(res.data);
  isLoading.value = false;
  total.value = res.total;
};
getList();
//删除(多选 | 单个)
const remove = (isOne, record) => {
  console.log(isOne, record);
  const params = [];
  let message = "";
  if (isOne) {
    // 单选
    const { name, id } = record;
    params.push(id);
    message = name;
  } else {
    // 多选
    const ids = selectedData.value.map((item) => item.id);
    params.push(...ids);
    message = ids.length + "条数据";
  }
  // 1.拦截弹框
  Modal.confirm({
    title: "温馨提示",
    icon: createVNode(ExclamationCircleOutlined),
    content: `是否删除选中的数据？【${message}】`,
    async onOk() {
      try {
        return await delBannerApi(params).then((res) => {
          if (res.affected > 0) {
            //删除成功
            Msg.success("删除成功");
            // getList();
          } else {
            //删除失败
            Msg.fail("删除失败");
          }
          //刷新页面
          getList();
        });
      } catch (e) {
        // return message.error("操作有误");
      }
    },
    onCancel() {},
    maskClosable: true,
  });
};
// 多选
const rowSelection = ref({
  checkStrictly: false,
  onChange: (selectedRowKeys, selectedRows) => {
    selectedData.value = selectedRows;
    console.log(
      `selectedRowKeys: ${selectedRowKeys}`,
      "selectedRows: ",
      selectedRows
    );
  },
  onSelect: (record, selected, selectedRows) => {
    selectedData.value = selectedRows;
    console.log(record, selected, selectedRows);
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    selectedData.value = selectedRows;
    console.log(selected, selectedRows, changeRows);
  },
});
//添加
const router = useRouter();
const toAdd = () => {
  router.push({ name: "bannerAdd" });
};
// 编辑
const toEdiort = ({ id }) => {
  router.push({ name: "bannerEdit", params: { id } });
};

// 搜索
const onSearch = () => {
  getList();
};
</script>

<style scoped lang="less">
.banner {
  margin-top: 10px;
  padding: 0 20px;
  .banner_top {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .search {
      max-width: 300px;
    }
  }
  .footer {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
  }
}
</style>
